﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using Xceed.Wpf.Toolkit;

namespace LanguagePolish
{
    public static class WpfHelper
    {
        public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
        {
            if (depObj != null)
            {
                for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
                {
                    DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
                    if (child != null && child is T)
                    {
                        yield return (T)child;
                    }

                    foreach (T childOfChild in FindVisualChildren<T>(child))
                    {
                        yield return childOfChild;
                    }
                }
            }
        }

        /// <summary>
        /// Вызывает принудительное обновление и валидацию связанных свойств дочерних элементов указанного контейнера.
        /// </summary>
        /// <param name="root"></param>
        public static void ForcedValidation(DependencyObject root)
        {
            foreach (var cmb in FindVisualChildren<ComboBox>(root))
            {
                var bindingExpression = cmb.GetBindingExpression(ComboBox.SelectedItemProperty);
                if (bindingExpression != null)
                    bindingExpression.UpdateSource();
            }
            foreach (var txt in FindVisualChildren<TextBox>(root))
            {
                var bindingExpression = txt.GetBindingExpression(TextBox.TextProperty);
                if (bindingExpression != null)
                    bindingExpression.UpdateSource();
            }
            foreach (var tp in FindVisualChildren<TimePicker>(root))
            {
                var bindingExpression = tp.GetBindingExpression(TimePicker.ValueProperty);
                if (bindingExpression != null)
                    bindingExpression.UpdateSource();
            }
        }
    }
}
